package com.cskaoyan.market.intercepter;

import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenticateIntercepter_bak implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // /admin/auth/login  /admin/auth/logout不需认证，其他接口需要进行认证
        //如果是除了上述这两个地址之外的请求地址，那么全部需要进行认证，也就是仅登录之后才可以访问
        //当前的请求资源路径
        String requestURI = request.getRequestURI();
        if(requestURI.equals(request.getContextPath() + "/admin/auth/login")
                || requestURI.equals(request.getContextPath() + "/admin/auth/logout")
                || requestURI.equals(request.getContextPath() + "/wx/auth/login")
                || requestURI.equals(request.getContextPath() + "/wx/auth/logout")
        ){
            //只要是上述中任何一个地址，那么放行
            System.out.println("登录放行");
            return true;
        }
        //如果不是上述两个中的任意一个路径，那么需要进行认证，判断是否登录
        HttpSession session = request.getSession();
        System.out.println(session);
        Object admin = session.getAttribute("admin");
        if(admin == null){
            //没有登录
            System.out.println("没有登录");
            response.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.unlogin()));
            return false;
        }
        //登录
        System.out.println("认证成功" + admin);
        return true;
    }
}
